<template>
  <div class="bank" v-show="!isQuiz">
    <div class="left">
      <div class="quesCard">
        <div class="quesCard-header">
          <div class="row">
            <OjSelect class="diff" clearable placeholder="请选择难度" :options="difficultyLevel" @ojChange="(v) => {
              searchParams.difficulty = v || -1
              getProblemList()
            }"></OjSelect>
            <OjSearch placeholder="搜索题目" size="small" @search="(v) => searchData(v)"></OjSearch>
            <n-checkbox class="isShowTag" v-model:checked="isShowTag">
              显示标签
            </n-checkbox>
            <n-button class="reset-btn" round strong secondary type="primary" @click="resetParams">
              <i class="iconfont icon-htmal5icon23"></i>
              重置
            </n-button>
          </div>
        </div>
        <div class="quesCard-body">
          <el-table :data="problem.records" stripe class="problemTable no-background"
            @cell-mouse-enter="updateCurrentProblem" @row-click="(row) => { hanlderToProbDetail(row.id) }">
            <el-table-column width="40px" align="center">
              <template #default="scoped">
                <div class="status" v-show="problemStatusList[scoped.row.id] != undefined">
                  <i class="iconfont icon-gou ac" v-if="problemStatusList[scoped.row.id] == 'Accepted'"></i>
                  <i class="iconfont icon-henggang se" v-else-if="
                    problemStatusList[scoped.row.id] == 'System Error'
                  "></i>
                  <i class="iconfont icon-henggang blue" v-else-if="
                    problemStatusList[scoped.row.id] == 'Partial Accepted'
                  "></i>
                  <i class="iconfont icon-henggang orange" v-else-if="
                    problemStatusList[scoped.row.id] ==
                    'Presentation Error' ||
                    problemStatusList[scoped.row.id] == 'Compile Error'
                  "></i>
                  <i class="iconfont icon-chahao1 red" v-else></i>
                </div>
              </template>
            </el-table-column>
            <el-table-column type="index" label="序号" width="60px" align="center"
              :index="(index) => (searchParams.pageNum - 1) * searchParams.pageSize + index + 1" />
            <el-table-column prop="problemId" label="题目ID">
              <template #default="scoped">
                <n-ellipsis style="max-width: 120px">
                  {{ scoped.row.problemId }}
                </n-ellipsis>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="题目">
            </el-table-column>
            <el-table-column prop="difficulty" label="难度" align="center">
              <template #default="scoped">
                <el-tag v-for="item in difficultyLevel" :key="item.value" round size="small" :type="item.type"
                  v-show="scoped.row.difficulty === item?.value">{{ item.label }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="标签" v-if="isShowTag" align="center">
              <template #default="scoped">
                <n-tag class="title-tag" size="small" v-for="(item, index) in scoped.row.tagList || []"
                  :key="`${scoped.row.problemId}${index}`" :color="{
                    color: item?.color,
                    textColor: item?.color,
                    borderColor: item?.color,
                  }">
                  {{ item?.name ? item?.name : '--' }}
                </n-tag>
              </template>
            </el-table-column>

            <el-table-column prop="ioScore" label="分数" align="center" />
            <el-table-column prop="submitCount" label="总数" align="center" />
            <el-table-column prop="ioScore" label="通过率" align="center">
              <template #default="scoped">
                <n-progress type="line" indicator-placement="inside" :percentage="getPercent(scoped.row.acCount, scoped.row.submitCount)
                  " color="rgb(105,187,98)" indicator-text-color="black"></n-progress>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pageNation">
          <el-pagination class="pagination" :page-sizes="[20, 50, 100]" background small
            layout="prev, pager, next,sizes" :total="Number(problem.total)" v-model:current-page="searchParams.pageNum"
            v-model:page-size="searchParams.pageSize" @change="() => {
              router.push({ query: { ...searchParams } })
            }" />
        </div>
      </div>
    </div>
    <div class="right">
      <div class="dataCard" :style="{ height: store.oj.systemParams.screenHeight * 0.5 + 'px' }">
        <div class="title">{{ currentProblem.title || "请选择题目" }}</div>
        <div id="myChart" class="myEcahrts"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeMount } from 'vue'
import { getProblemListAPI, getProblemStatusAPI } from '@/api/ojAPI/ojAPI'
import * as echarts from 'echarts'
import OjSearch from '@/components/common/ojSearch.vue'
import OjSelect from '@/components/common/ojSelect.vue'
import { useRoute, useRouter } from 'vue-router'
import useStore from "@/store"
import { chartConfig, difficultyLevel } from './config'

const router = useRouter()
const route = useRoute()

const store = useStore()

const problem = ref({
  records: [],
  total: 10,
})
const searchParams = ref({
  pageNum: Number(route.query.pageNum) || 1,
  pageSize: Number(route.query.pageSize) || 20,
  difficulty: Number(route.query.difficulty) || -1,
  name: route.query.name || "",
})
const isQuiz = ref(false)
const isShowTag = ref(false)
const currentProblem = ref({})
const problemStatusList = ref({})
const myChart = ref(null)
const timer = ref(null)

onMounted(() => {
  myChart.value = echarts.init(document.getElementById('myChart'))
  getProblemList()
  initEcharts()
})
watch(() => route.query, (val) => {
  searchParams.value = {
    pageNum: Number(val.pageNum) || 1,
    pageSize: Number(val.pageSize) || 20,
    difficulty: Number(val.difficulty) || -1,
    name: val.name || "",
  }
  getProblemList()
}, { deep: true })

const getProblemList = () => {
  setTimeout(async () => {
    try {
      const response = await getProblemListAPI(searchParams.value)
      if (response.data.code === 200) {
        if (response.data.data === null) {
          problem.value.records = []
          problem.value.total = 1
          return
        }
        problem.value.records = response.data.data.records
        problem.value.total = Number(response.data.data.total)
        const ids = problem.value.records.map((ele) => ele.id)
        await getProblemStatus(ids)
      }
    } catch (err) {
      console.error(err)
    }
  }, 100)
}

const hanlderToProbDetail = (id) => {
  router.push({ path: `/home/bank/${id}` }).then(() => {
    isQuiz.value = true
  })
}

const resetParams = () => {
  searchParams.value = {
    pageNum: 1,
    pageSize: 20,
    difficulty: 0,
    name: "",
  }
  router.push({ query: { ...searchParams.value } })
}

const searchData = (v) => {
  searchParams.value = {
    pageNum: 1,
    pageSize: searchParams.value.pageSize,
    difficulty: searchParams.value.difficulty,
    name: v,
  }
  router.push({ query: { ...searchParams.value } })
}

const getPercent = (acCount, problemCount) => {
  if (problemCount === 0) {
    return 0
  }
  return +Number((((acCount * 100) / problemCount) * 100) / 100).toFixed(2)
}

const initEcharts = (data = [
  { value: 100, name: "AC" },
  { value: 100, name: "PAC" },
  { value: 100, name: "UAC" },
  { value: 100, name: "CE" },
  { value: 100, name: "..." },
]) => {
  const conf = chartConfig
  conf.series[0].data = data
  myChart.value.setOption(conf)
}

const updateCurrentProblem = (row) => {
  currentProblem.value = row
  initEcharts([
    { value: row.acCount, name: "AC" },
    { value: row.pacCount, name: "PAC" },
    { value: row.uacCount, name: "UAC" },
    { value: row.ceCount, name: "CE" },
    {
      value:
        (row.submitCount -
          row.acCount -
          row.uacCount -
          row.ceCount -
          row.pacCount),
      name: "...",
    },
  ])
}

const getProblemStatus = async (ids) => {
  if (!store.oj.isLogin) {
    return
  }
  try {
    const response = await getProblemStatusAPI(ids)
    if (response.data.code === 200) {
      problemStatusList.value = response.data.data
    }
  } catch (err) {
    console.error(err)
  }
}
</script>

<style lang="less" scoped>
.bank {
  width: 99%;
  max-height: 85vh;
  display: flex;
  margin: 0 auto;

  .left {
    width: 74%;

    .quesCard {
      width: 96%;
      height: 100%;
      margin: 0 auto;
      border-radius: 16px;
      // background: #ffffff;
      padding: 10px;
      display: flex;
      flex-direction: column;

      .quesCard-header {
        width: 100%;
        height: 50px;
        border-bottom: 2px solid @lineColor;

        .row {
          width: 100%;
          height: 30px;
          line-height: 30px;
          align-items: center;
          display: flex;
          margin: 5px 0;

          .title {
            color: #555;
            font-weight: 600;
            text-align: center;
            height: 30px;
            line-height: 30px;
            margin: auto 0 auto 1%;
            display: flex;

            .iconfont {
              font-size: 24px;
            }

            .title-text {
              font-size: 22px;
            }
          }

          .diff {
            width: 10%;
            margin: auto 10px auto 0;
          }

          .search {
            width: 25%;
            display: flex;
            height: 30px;
            line-height: 30px;
            margin: auto 0;

            .search-input {
              width: 100%;
              margin: auto 0 0 0;

              .iconfont {
                cursor: pointer;
              }
            }
          }

          .isShowTag {
            height: 30px;
            line-height: 30px;
            margin: auto;
          }

          .reset-btn {
            height: 30px;
            line-height: 30px;
            margin: auto 2% auto auto;
          }
        }
      }

      .quesCard-body {
        width: 100%;
        height: 86%;

        .problemTable {
          width: 100%;
          height: 100%;

          .status {
            display: flex;
            justify-content: center;

            .ac {
              color: rgb(58, 159, 85);
            }

            .se {
              color: grey;
            }

            .red {
              color: rgb(228, 103, 102);
            }

            .blue {
              color: rgb(85, 158, 255);
            }

            .orange {
              color: orange;
            }
          }

          .title-tag {
            background-color: rgb(252, 252, 253);
            margin-right: 4px;
          }
        }
      }

      .pageNation {
        width: 96%;
        height: 6%;
        min-height: 40px;
        line-height: 40px;
        margin: auto;
        display: flex;
        justify-content: center;
      }
    }
  }

  .right {
    width: 23%;

    .dataCard {
      width: 100%;
      border-radius: 16px;
      padding: 10px;

      .title {
        height: 5%;
        font-size: 18px;
        font-weight: 550;
        text-align: center;
      }

      .myEcahrts {
        width: 100%;
        height: 95%;
      }
    }
  }
}
</style>
